<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Ad;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class AdController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Ad(), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('title', '标题');
            $grid->column('img')->image();
            $grid->column('type');
            $grid->column('status', '状态')->switch();
            $grid->column('href', '跳转链接')->link();
            $grid->column('created_at', '创建时间');
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('type')->select(Ad::getTypeOptions());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Ad(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('img')->image();
            $show->field('type');
            $show->field('status', '状态');
            $show->field('href', '跳转链接');
            $show->field('created_at', '创建时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Ad(), function (Form $form) {
            $form->disableViewButton();
            $form->disableViewCheck();
            $form->display('id');
            $form->text('title', '标题');
            $form->image('img')->saveAsString()->saveFullUrl()->autoUpload()->rules('required', ['required' => '请上传广告图'])->saving(function ($path) {
                return httpToHttps($path);
            });
            $form->radio('is_jump', '是否跳转')->options([0 => '否', 1 => '是'])->default(0)
                ->when(1, function (Form $form) {
                    $form->url('href', '跳转链接')
                        ->rules('required_if:is_jump,1', ['required_if' => '请补充完整该项']);
                });
            $form->select('type')->options(Ad::getTypeOptions())->rules('required', ['required' => '请补充完整该项']);
            $form->radio('status', '状态')->options(['1' => '启用', '0' => '停用'])->default('1');
            $form->display('created_at');
        });
    }
}
